package com.edmendst.xmall.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JWTUtil {


    @Getter
    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

    @Autowired
    private RedisTemplate redisTemplate;
//    @PostConstruct
//    public void init() {
//        if (secret == null) {
//            throw new IllegalStateException("jwt.secret 未正确配置！");
//        }
//        System.out.println("JWT Secret 已加载: " + secret);
//    }

    public JWTUtil() {
        System.out.println("JWTUtil 已被调用");
    }



    //生成token
    public String generateToken(String username, String role) {
        System.out.println("generateToken - secret: " + secret); // 添加日志
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("username", username);
        claims.put("role", role);
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    //解析token
    public String getUserNameFromToken(String token) {
        System.out.println("getUserNameFromToken - secret: " + secret); // 添加日志
        if (secret == null) {
            throw new IllegalStateException("secret 为 null1");
        }
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        Object username = claims.get("username");
        Object object = claims.get("role");
        if (username != null&&username instanceof String) {
            return (String) username;
        }
        System.out.println("username为空或者格式不对");
        return null;
    }

    //验证token是否有效
    public boolean validateToken(String token) {
        System.out.println("validateToken - secret: " + secret); // 添加日志
        if (secret == null) {
            throw new IllegalStateException("secret 为 null2");
        }
        try {
            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            return true;
        }catch (Exception e) {
            e.printStackTrace(); // 打印详细异常信息
            return false;
        }
    }

    // 添加解析claims的方法
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

//获取剩余有效时间
    public long getRemainingTime(String token) {
        Claims claims = parseToken(token);
        Date expiration = claims.getExpiration();
        long currentTimeMillis = System.currentTimeMillis();
        long remainingTimeMillis = expiration.getTime() - currentTimeMillis;
        return remainingTimeMillis>0?remainingTimeMillis:0;
    }
}